import { createApp, ref, computed, onMounted } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import { storage } from './utils/storage.js'
import { exportToExcel } from './utils/excel.js'
import { ElMessage } from 'element-plus'
import './styles/main.css'

const app = createApp({
  setup() {
    const orders = ref([])
    const loading = ref(true)

    // 计算总金额
    const totalMoney = computed(() => {
      return orders.value.reduce((sum, order) => sum + order.totalAmount, 0)
    })

    // 加载订单
    const loadOrders = () => {
      try {
        orders.value = storage.getOrders()
        console.log('Loaded orders:', orders.value)
      } catch (error) {
        console.error('Error loading orders:', error)
        ElMessage.error('加载订单失败')
      } finally {
        loading.value = false
      }
    }

    // 导出Excel
    const exportOrders = () => {
      if (orders.value.length === 0) {
        ElMessage.warning('暂无数据可导出')
        return
      }
      try {
        exportToExcel(orders.value, '家具订单_前端')
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('Export error:', error)
        ElMessage.error('导出失败')
      }
    }

    onMounted(() => {
      console.log('App mounted')
      try {
        storage.initSampleData()
        loadOrders()
      } catch (error) {
        console.error('Mount error:', error)
        loading.value = false
      }
    })

    return {
      orders,
      loading,
      totalMoney,
      exportOrders
    }
  }
})

app.use(ElementPlus)

try {
  app.mount('#app')
  console.log('App initialized successfully')
} catch (error) {
  console.error('Mount failed:', error)
}
